package cn.wit.summit.chwan.adapters;

import android.content.Context;
import android.graphics.Color;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.util.List;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.dto.CommentBaseBean;
import cn.wit.summit.chwan.models.event.DeleteOrModifyCommentEvent;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.DateUtils;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.UtilsMy;
import cn.wit.summit.chwan.widgets.MStarBar;
import cn.wit.summit.chwan.widgets.VipView;

/**
 * Created by tangbl on 2017/9/11.
 */

public class CommentAllListAdapter extends BaseAdapter {

    private Context mContext;
    private List<ViewBean> itemBeans;
    private int uid;
    private String commentScoreSwitch;
    private int sgcSwitch;
    private int myCommentPosition = -1;

    public CommentAllListAdapter(Context mContext, int uid, List<ViewBean> itemBeans, String commentScoreSwitch, int sgcSwitch, Listener mListenr) {
        this.mContext = mContext;
        this.uid = uid;
        this.commentScoreSwitch = commentScoreSwitch;
        this.sgcSwitch = sgcSwitch;
        this.itemBeans = itemBeans;
        this.mListenr = mListenr;
    }

    public int getMyCommentPosition() {
        if (myCommentPosition==-1) {
            for (int i=0;i<itemBeans.size();i++) {
                if (itemBeans.get(i).getViewType()==ViewType.COMMENT &&
                        ((ViewBean.Comment)itemBeans.get(i).getObj()).data.getUid().equals(String.valueOf(uid))) {
                    myCommentPosition = i;
                    break;
                }
            }
        }
        return myCommentPosition;
    }

    public ViewBean.Comment getMyComment() {
        return (ViewBean.Comment) getItem(myCommentPosition);
    }

    public void changeMyComment(DeleteOrModifyCommentEvent event) {
        if (myCommentPosition==-1)
            return;
        if (event.getType()==1) {
            itemBeans.remove(myCommentPosition);
        } else {
            ViewBean.Comment viewBean = (ViewBean.Comment) getItem(myCommentPosition);
            viewBean.data.setContent(event.getContentStr());
//            viewBean.data.setAdd_times(String.valueOf(event.getTime()));
            viewBean.data.setMobile_phone_model(event.getMobileType());
            viewBean.data.setStars_score(String.valueOf(event.getStarNum()));
        }
        this.notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (itemBeans != null) {
            return itemBeans.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (itemBeans != null) {
            return itemBeans.get(position).getObj();
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        return ViewType.values().length;
    }

    @Override
    public int getItemViewType(int position) {
        if (this.itemBeans != null) {
            ViewBean bean = this.itemBeans.get(position);
            return bean.getViewType().ordinal();
        }
        return -1;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        int type = getItemViewType(position);

        if (type == ViewType.COMMENT.ordinal()) {
            view = getCommentView(position, view, viewGroup, 2);
        } else if (type == ViewType.TITLE.ordinal()) {
            view = getCommentView(position, view, viewGroup, 1);
        }

        return view;
    }

    private View getCommentView(int position, View view, ViewGroup viewGroup, int type) {
        ViewBean.Comment viewBean = (ViewBean.Comment) getItem(position);

        ViewHolderTitle viewHolderTitle = null;
        CommentViewHolder commentViewHolder = null;

        if (view == null) {
            switch (type) {
                case 1:
                    viewHolderTitle = new ViewHolderTitle();
                    view = LayoutInflater.from(mContext).inflate(R.layout.gamedetail_item_title, null);
                    viewHolderTitle.titleText = (TextView) view.findViewById(R.id.titleText);
                    viewHolderTitle.layoutTop = view.findViewById(R.id.layoutTop);
                    view.setTag(viewHolderTitle);
                    break;
                case 2:
                    commentViewHolder = new CommentViewHolder();
                    view = LayoutInflater.from(mContext).inflate(R.layout.comment_list_item_view, null);
                    commentViewHolder.commentAllRootLl = (LinearLayout) view.findViewById(R.id.commentAllRootLl);
                    commentViewHolder.userIcon = (SimpleDraweeView) view.findViewById(R.id.usericon);
                    commentViewHolder.userName = (TextView) view.findViewById(R.id.userName);
                    commentViewHolder.isMe = (TextView) view.findViewById(R.id.isMe);
                    commentViewHolder.levelTv = (VipView) view.findViewById(R.id.levelTv);
                    commentViewHolder.isAuth = (ImageView) view.findViewById(R.id.isAuth);
                    commentViewHolder.isGood = (ImageView) view.findViewById(R.id.isGood);
                    commentViewHolder.isConnoisseurs = (TextView) view.findViewById(R.id.isConnoisseurs);
                    commentViewHolder.comment_head_mstarBar = (MStarBar) view.findViewById(R.id.comment_head_mstarBar);
                    commentViewHolder.comment_head_num_tx = (TextView) view.findViewById(R.id.comment_head_num_tx);
                    commentViewHolder.time = (TextView) view.findViewById(R.id.time);
                    commentViewHolder.content = (TextView) view.findViewById(R.id.content);
                    commentViewHolder.more = (TextView) view.findViewById(R.id.more);
                    commentViewHolder.line = view.findViewById(R.id.line);
                    commentViewHolder.phoneModle = (TextView) view.findViewById(R.id.phoneModle);
                    commentViewHolder.parise = (ImageView) view.findViewById(R.id.parise);
                    commentViewHolder.pariseNumber = (TextView) view.findViewById(R.id.pariseNumber);
                    commentViewHolder.down = (ImageView) view.findViewById(R.id.down);
                    commentViewHolder.downNumber = (TextView) view.findViewById(R.id.downNumber);
                    commentViewHolder.message = (ImageView) view.findViewById(R.id.message);
                    commentViewHolder.messageNumber = (TextView) view.findViewById(R.id.messageNumber);
                    view.setTag(commentViewHolder);
                    break;
            }
        } else {
            switch (type) {
                case 1:
                    viewHolderTitle = (ViewHolderTitle) view.getTag();
                    break;
                case 2:
                    commentViewHolder = (CommentViewHolder) view.getTag();
                    break;
            }
        }

        if (viewBean == null)
            return view;

        final CommentBaseBean commitDataBean = viewBean.data;
        switch (type) {
            case 1:
                if (commitDataBean.getIs_hot() == 1) {
                    viewHolderTitle.titleText.setText("热门点评");
                } else {
                    viewHolderTitle.titleText.setText("最新点评");
                }
                viewHolderTitle.layoutTop.setVisibility(View.GONE);
                break;
            case 2:
                if (viewBean == null) return null;

                commentViewHolder.userName.setTextColor(Color.BLACK);
                if (commitDataBean.getVip_level()>0)
                    commentViewHolder.userName.setTextColor(mContext.getResources().getColor(R.color.vip_color));

                if (commitDataBean.getSvip_level()>0)
                    commentViewHolder.userName.setTextColor(mContext.getResources().getColor(R.color.vip_svip_color));

                commentViewHolder.levelTv.setVipData(commitDataBean.getVip_level(), commitDataBean.getSvip_level());

                if (commitDataBean.getUid().equals(String.valueOf(uid))) {
                    commentViewHolder.isMe.setVisibility(View.VISIBLE);
                    myCommentPosition = position;
                } else {
                    commentViewHolder.isMe.setVisibility(View.GONE);
                }

                commentViewHolder.userName.setText(commitDataBean.getUser_name());
                if (android.os.Build.VERSION.SDK_INT == 19) {
                    commentViewHolder.content.setText(commitDataBean.getContent().replaceAll("\n",""));
                } else {
                    commentViewHolder.content.setText(commitDataBean.getContent());
                }
                if (commitDataBean.getIs_old() == 1 || commitDataBean.getMobile_phone_model()==null
                        || commitDataBean.getMobile_phone_model().isEmpty())
                    commentViewHolder.phoneModle.setVisibility(View.INVISIBLE);
                else {
                    commentViewHolder.phoneModle.setVisibility(View.VISIBLE);
                    commentViewHolder.phoneModle.setText(commitDataBean.getMobile_phone_model());
                }
                commentViewHolder.pariseNumber.setText(commitDataBean.getPraise_count()+"");
                commentViewHolder.downNumber.setText(commitDataBean.getDespise_count()+"");
                commentViewHolder.messageNumber.setText(commitDataBean.getReply_count()+"");
                long timel = Long.parseLong(commitDataBean.getAdd_times() + "000");
                commentViewHolder.time.setText(DateUtils.FormatForDownloadTime(timel));

                if (commitDataBean.getIs_old()==1 || Float.valueOf(commitDataBean.getStars_score())==0
                        || (commentScoreSwitch!=null && !commentScoreSwitch.equals("1"))) {
                    commentViewHolder.comment_head_mstarBar.setVisibility(View.GONE);
                } else {
                    commentViewHolder.comment_head_mstarBar.setVisibility(View.VISIBLE);
                    commentViewHolder.comment_head_mstarBar.setStarCount(Integer.parseInt(commitDataBean.getStars_score()));
                    commentViewHolder.comment_head_mstarBar.setStarMark(Float.valueOf(commitDataBean.getStars_score()));
                }

//                if (commitDataBean.getIs_old()==1) {
//                    commentViewHolder.comment_head_num_tx.setVisibility(View.GONE);
//                } else {
//                    commentViewHolder.comment_head_num_tx.setVisibility(View.VISIBLE);
//                    commentViewHolder.comment_head_num_tx.setText("启动游戏 "+commitDataBean.getStart_game_count()+" 次");
//                }

                if (sgcSwitch==1) {
                    if (commitDataBean.getIs_old() == 0) {
                        commentViewHolder.comment_head_num_tx.setVisibility(View.VISIBLE);
                        commentViewHolder.comment_head_num_tx.setText("启动游戏 " + commitDataBean.getStart_game_count() + " 次");
                    } else {
                        commentViewHolder.comment_head_num_tx.setVisibility(View.GONE);
                    }
                } else {
                    commentViewHolder.comment_head_num_tx.setVisibility(View.GONE);
                }

                commentViewHolder.comment_head_mstarBar.setEnabled(false);

                if (commitDataBean.getApproval_rate()!=null
                        && Double.valueOf(commitDataBean.getApproval_rate())>70)
                    commentViewHolder.isGood.setVisibility(View.VISIBLE);
                else
                    commentViewHolder.isGood.setVisibility(View.GONE);

                if (commitDataBean.getRank().equals("")) {
                    commentViewHolder.isAuth.setVisibility(View.GONE);
                } else {
                    commentViewHolder.isAuth.setVisibility(View.VISIBLE);
                }
                commentViewHolder.isConnoisseurs.setText(commitDataBean.getRank());

                if (commitDataBean.getIs_praise()==1) {
                    commentViewHolder.parise.setImageResource(R.drawable.uped_ic);
                } else {
                    commentViewHolder.parise.setImageResource(R.drawable.up_ic);
                }

                if (commitDataBean.getIs_despise()==1) {
                    commentViewHolder.down.setImageResource(R.drawable.downed_ic);
                } else {
                    commentViewHolder.down.setImageResource(R.drawable.down_ic);
                }

                    UtilsMy.setIconImage(mContext, commitDataBean.getHead_portrait(), commentViewHolder.userIcon);

                setOnPraiseListener(commentViewHolder.parise, commentViewHolder.pariseNumber, commitDataBean, position);
                setOnUnPraiseListener(commentViewHolder.down, commentViewHolder.downNumber, commitDataBean, position);
                setOnItemListener(commentViewHolder.message, commitDataBean);
                setOnItemListener(commentViewHolder.commentAllRootLl, commitDataBean);

                final CommentViewHolder finalCommentViewHolder1 = commentViewHolder;
                commentViewHolder.content.post(new Runnable() {
                    @Override
                    public void run() {
                        Layout l = finalCommentViewHolder1.content.getLayout();
                        if(l!=null){
                            int lines =l.getLineCount();
                            if(lines>0){
                                if(l.getEllipsisCount(lines-1)>0){
                                    finalCommentViewHolder1.more.setVisibility(View.VISIBLE);
                                } else {
                                    finalCommentViewHolder1.more.setVisibility(View.GONE);
                                }
                            }
                        } else {
                            finalCommentViewHolder1.more.setVisibility(View.GONE);
                        }
                    }
                });
                final CommentViewHolder finalCommentViewHolder = commentViewHolder;
                commentViewHolder.more.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String s = finalCommentViewHolder.more.getText().toString();
                        if (s.equals("查看全部")) {
                            if (android.os.Build.VERSION.SDK_INT == 19) {
                                finalCommentViewHolder.content.setText(commitDataBean.getContent());
                            }
                            finalCommentViewHolder.content.setMaxLines(Integer.MAX_VALUE);
                            finalCommentViewHolder.more.setText("收起");
                        } else {
                            if (android.os.Build.VERSION.SDK_INT == 19) {
                                finalCommentViewHolder.content.setText(commitDataBean.getContent().replaceAll("\n", ""));
                            }
                            finalCommentViewHolder.content.setMaxLines(5);
                            finalCommentViewHolder.more.setText("查看全部");
                        }
                    }
                });
                break;
        }

        return view;
    }

    private void setOnItemListener(View view, final CommentBaseBean commitDataBean) {
        view.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (commitDataBean==null)
                    return;
                if (mListenr != null) {
                    mListenr.onRootView(commitDataBean);
                }
            }
        });
    }

    private void setOnPraiseListener(final ImageView view, final TextView tv, final CommentBaseBean commitDataBean, final int position) {
        View.OnClickListener temp = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                if (AccountUtil_.getInstance_(mContext).isTourist()) {
//                    DialogUtil_.getInstance_(mContext).getAccountLoginDialogForCommon(mContext,
//                            mContext.getResources().getString(R.string.comment_login_tx), "登录", "取消", null);
//                    return;
//                }

                if (AccountUtil.getInstance().getUid()==0) {
                    IntentUtil.getInstance().goLoginActivity(mContext);
                    return;
                }
                if (commitDataBean==null)
                    return;
                if (commitDataBean.getIs_praise()==1) {
                    subPraise(position);
                    view.setImageResource(R.drawable.up_ic);
                    if (mListenr != null) {
                        mListenr.onPraise(commitDataBean, position, 2);
                    }
                    return;
                } else {
                    commitDataBean.setIs_praise(1);
                }

                if (AccountUtil.getInstance().getAccountData() != null) {
                    view.setImageResource(R.drawable.uped_ic);
                    Animation scaleAnim = AnimationUtils.loadAnimation(mContext, R.anim.scale_reset);
                    view.startAnimation(scaleAnim);
                    scaleAnim.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            long num = Long.valueOf(tv.getText().toString());
                            tv.setText((num+1)+"");
                            addPraise(position);

                            if (mListenr != null) {
                                mListenr.onPraise(commitDataBean, position, 1);
                            }
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                } else {
//                    IntentUtil.getInstance().goMyAccountLoginActivity(mContext, 0, 2);
                    IntentUtil.getInstance().goLoginInteractive(mContext);
                }
            }
        };

        view.setOnClickListener(temp);
        tv.setOnClickListener(temp);
    }

    public void addPraise(int position) {
        ViewBean.Comment viewBean = (ViewBean.Comment) getItem(position);

        long num = viewBean.data.getPraise_count();
        viewBean.data.setIs_praise(1);
        viewBean.data.setPraise_count(num+1);
        notifyDataSetChanged();
    }

    public void subPraise(int position) {
        ViewBean.Comment viewBean = (ViewBean.Comment) getItem(position);

        long num = viewBean.data.getPraise_count();
        viewBean.data.setIs_praise(0);
        if (num-1<0)
            viewBean.data.setPraise_count(0);
        else
            viewBean.data.setPraise_count(num-1);
        notifyDataSetChanged();
    }

    public void resetPraise(int position, int state) {
        ViewBean.Comment viewBean = (ViewBean.Comment) getItem(position);

        long num = viewBean.data.getPraise_count();
        if (viewBean.data.getIs_praise()==1) {
            viewBean.data.setIs_praise(0);
            if (num-1<0)
                viewBean.data.setPraise_count(0);
            else
                viewBean.data.setPraise_count(num-1);
        } else {
            if (state!=1) {
                viewBean.data.setIs_praise(1);
                viewBean.data.setPraise_count(num+1);
            }
        }
        notifyDataSetChanged();
    }

    public void resetDespise(int position, int state) {
        ViewBean.Comment viewBean = (ViewBean.Comment) getItem(position);
        long num = Long.valueOf(viewBean.data.getDespise_count());
        if (viewBean.data.getIs_despise()==1) {
            viewBean.data.setIs_despise(0);
            if (num-1<0)
                viewBean.data.setDespise_count("0");
            else
                viewBean.data.setDespise_count(num-1+"");
        } else {
            if (state!=1) {
                viewBean.data.setIs_despise(1);
                viewBean.data.setDespise_count(num+1+"");
            }
        }
        notifyDataSetChanged();
    }

    public void addDespise(int position) {
        ViewBean.Comment viewBean = (ViewBean.Comment) getItem(position);

        long num = Long.valueOf(viewBean.data.getDespise_count());
        viewBean.data.setIs_despise(1);
        viewBean.data.setDespise_count(num+1+"");
        notifyDataSetChanged();
    }

    public void subDespise(int position) {
        ViewBean.Comment viewBean = (ViewBean.Comment) getItem(position);

        long num = Long.valueOf(viewBean.data.getDespise_count());
        viewBean.data.setIs_despise(0);
        if (num-1<0)
            viewBean.data.setDespise_count("0");
        else
            viewBean.data.setDespise_count(num-1+"");
        notifyDataSetChanged();
    }

    private void setOnUnPraiseListener(final ImageView view, final TextView tv, final CommentBaseBean commitDataBean, final int position) {
        View.OnClickListener temp = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                if (AccountUtil_.getInstance_(mContext).isTourist()) {
//                    DialogUtil_.getInstance_(mContext).getAccountLoginDialogForCommon(mContext,
//                            mContext.getResources().getString(R.string.comment_login_tx), "登录", "取消", null);
//                    return;
//                }
                if(IntentUtil.getInstance().goLoginInteractive(mContext))return;
                if (commitDataBean==null)
                    return;
                if (commitDataBean.getIs_despise()==1) {
                    subDespise(position);
                    view.setImageResource(R.drawable.down_ic);
                    if (mListenr != null) {
                        mListenr.onUnPraise(commitDataBean, position, 2);
                    }
                    return;
                } else {
                    commitDataBean.setIs_despise(1);
                }

                if (AccountUtil.getInstance().getAccountData() != null) {
                    view.setImageResource(R.drawable.downed_ic);
                    Animation scaleAnim = AnimationUtils.loadAnimation(mContext, R.anim.scale_reset);
                    view.startAnimation(scaleAnim);
                    scaleAnim.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            long num = Long.valueOf(tv.getText().toString());
                            tv.setText((num+1)+"");
                            addDespise(position);

                            if (mListenr != null) {
                                mListenr.onUnPraise(commitDataBean, position, 1);
                            }
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                } else {
//                    IntentUtil.getInstance().goMyAccountLoginActivity(mContext, 0, 2);
                    IntentUtil.getInstance().goLoginInteractive(mContext);
                }
            }
        };
        view.setOnClickListener(temp);
        tv.setOnClickListener(temp);
    }

    //region 事件回调
    Listener mListenr = null;

    public Listener getmListenr() {
        return mListenr;
    }

    public void setListenr(Listener mListenr) {
        this.mListenr = mListenr;
    }

    public interface Listener {

        void onPraise(CommentBaseBean bean, int position, int type);//点赞

        void onUnPraise(CommentBaseBean bean, int position, int type);//点踩

        void onRootView(CommentBaseBean bean);//item
    }

    class ViewHolder {

    }

    class ViewHolderTitle {
        public TextView titleText;
        public LinearLayout look_other;
        public View layoutTop;
        public View line_h;
    }

    class CommentViewHolder extends ViewHolder {
        private LinearLayout commentAllRootLl;
        private SimpleDraweeView userIcon;
        private TextView userName;
        private TextView isMe;
        private ImageView isAuth;
        private TextView isConnoisseurs;
        private MStarBar comment_head_mstarBar;
        private TextView comment_head_num_tx;
        private TextView time;
        private ImageView isGood;
        private TextView content;
        private TextView more;
        public View line;
        private TextView phoneModle;
        private ImageView parise;
        private TextView pariseNumber;
        private ImageView down;
        private TextView downNumber;
        private ImageView message;
        private TextView messageNumber;
        private VipView levelTv;
    }

    public enum ViewType {
        TITLE,
        COMMENT,
        REPLY
    }

    public static class ViewBean {
        ViewType viewType;
        Object obj;

        public ViewBean() {
        }

        public ViewBean(ViewType viewType, Object obj) {
            this.viewType = viewType;
            this.obj = obj;
        }

        public ViewType getViewType() {
            return viewType;
        }

        public void setViewType(ViewType viewType) {
            this.viewType = viewType;
        }

        public Object getObj() {
            return obj;
        }

        public void setObj(Object obj) {
            this.obj = obj;
        }

        public static class Comment {
            public CommentBaseBean data;

            public Comment(CommentBaseBean data) {
                this.data = data;
            }
        }

        public static class Reply {
            public String commentId;
            public CommentBaseBean commentBean;
            public int myAuth;
            public boolean showDivider;
            public int replyItemIndex;
            public boolean lastIndex;
            public boolean hideBottom;

            public Reply(String commentId, CommentBaseBean commentBean, int myAuth, boolean showDivider) {
                this.commentId = commentId;
                this.commentBean = commentBean;
                this.myAuth = myAuth;
                this.showDivider = showDivider;
            }
        }
    }
}
